<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/message.css">
    <title>我的消息</title>
</head>

<body>
    <!-- 导航栏start -->
    <header class="header">

        <div class="container-fluid">
            <div class="header_content">
                <!-- logo图 -->
                <div class="header_logo">
                    <a href="index.html">
                        <img src="images/logo.jpg" alt="LOGO">
                    </a>
                </div>
                <!-- 导航栏搜索 -->
                <form action="#" class="header_search ms-auto">
                    <input type="text" class="form-control" placeholder="搜你想要">
                    <button type="button">
                        <i class="fa fa-search"></i>
                      </button>
                </form>
                <!-- 导航栏中间按钮 -->
                <div class="header_menu">
                    <ul class="header_nav">
                        <li>
                            <a class="header_nav_link" href="index.html" role="button">首页推荐</a>
                        </li>
                        <li>
                            <a class="header_nav_link" href="#" role="button" id="digital-area">数码专区</a>
                        </li>
                        <li>
                            <a class="header_nav_link" href="message.html"" role="button">我的消息</a>
                        </li>
                    </ul>
                </div>
                <!-- 导航栏侧边 -->
                <div class="header_action">
                    <ul class="header_action_nav">
                        <li>
                            <div class="dropdown">
                                <a class="header_sign dropdown-toggle" id="login_region" href="#" role="button" data-toggle="dropdown" aria-expanded="false">登录/注册</a>
                                <div class="dropdown-menu" aria-labelledby="login">
                                    <a class="dropdown-item" id="dropdown-login-item" href="login.html">登录</a>
                                    <a class="dropdown-item" id="dropdown-exit-item">退出</a>
                                </div>
                            </div>
                        </li>
                        <li>
                            <a class="header_sign" role="button" id="person_center">个人中心</a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </header>
    <!-- 导航end -->

    <section>
        <div class="msg-section">
            <!-- 页面主体 -->
            <div class="msg-box">
                <!-- 左侧联系人 -->
                <div class="left-menu">
                    <div class="left-title">
                        <span>近期消息</span>
                    </div>
                    <div class="_view">
                        <div class="contacts-list">
                            <div v-for="(chater, index) in chaters" :key="chater.username">
                                <div class="list-item" @click="getchat(chater)">
                                    <div class="avatar">
                                        <img v-bind:src="chater.picture">
                                    </div>

                                    <div class="name-box">
                                        <div class="contact-name">{{chater.username}}</div>
                                        <div class="last-word"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧聊天框 -->
                <div class="right-content">
                    <div class="right-title">
                        <span>联系人名称({{chatUser}})</span>
                    </div>
                    <div class="message-list" v-html="content">

                    </div>
                    <div class="send-box">
                        <textarea v-model="text" style="height: 90px; width: 100%; padding: 20px; border: none; border-top: 1px solid #ccc;
                border-bottom: 1px solid #ccc; outline: none">
                    </textarea>
                        <div class="row">
                            <button class="send-btn" @click="send">发送</button>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </section>
</body>
<script src="js/jquery-3.6.0.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/bootstrap.bundle461.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/vue.js"></script>
<script>
    function getCookie(name) {
        // 拆分 cookie 字符串
        var cookieArr = document.cookie.split(";");

        // 循环遍历数组元素
        for (var i = 0; i < cookieArr.length; i++) {
            var cookiePair = cookieArr[i].split("=");

            /* 删除 cookie 名称开头的空白并将其与给定字符串进行比较 */
            if (name == cookiePair[0].trim()) {
                // 解码cookie值并返回
                return decodeURIComponent(cookiePair[1]);
            }
        }
        // 如果未找到，则返回null
        return null;
    }
    let socket
    $(document).ready(function() {
        var message = new Vue({
            el: '.msg-section',
            data: {
                circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
                user: {},
                isCollapse: false,
                users: [],
                chatUser: '',
                text: "",
                messages: [],
                content: '',
                chaters: [],
                mypicture: "",
                chatpicture: ""
            },
            created() {
                this.init()
            },
            computed: {

            },
            methods: {
                getchat(chater) {
                    if (this.chatUser != chater.username) {
                        this.content = "";
                        this.chatUser = chater.username;
                        this.chatpicture = chater.picture;
                        if(getCookie("if_user")==1)
                        {this.history_search_func(this.user.username, this.chatUser)}else{
                            this.history_search_func(this.chatUser, this.user.username)
                        }
                    }
                },
                send() {
                    if (!this.chatUser) {
                        alert("请选择聊天对象!")
                        return;
                    }
                    if (!this.text) {
                        alert("请输入聊天内容!")
                    } else {
                        if (typeof(WebSocket) == "undefined") {
                            console.log("您的浏览器不支持WebSocket");
                        } else {
                            console.log("您的浏览器支持WebSocket");
                            // 组装待发送的消息 json
                            // {"from": "zhang", "to": "admin", "text": "聊天文本"}
                            let message = {
                                from: this.user.username,
                                to: this.chatUser,
                                text: this.text
                            }
                            socket.send(JSON.stringify(message)); // 将组装好的json发送给服务端，由服务端进行转发
                            this.messages.push({
                                    user: this.user.username,
                                    text: this.text
                                })
                                // 构建消息内容，本人消息
                            this.createContent(null, this.user.username, this.text)
                            this.history_add_func(this.user.username, this.chatUser, this.text)
                            this.text = '';
                        }
                    }
                },
                createContent(remoteUser, nowUser, text) { // 这个方法是用来将 json的聊天消息数据转换成 html的。
                    let html
                    let _this=this
                        // 当前用户消息
                    if (nowUser) {
                        html = "<div class=\"msg-item is-me\">\n" +
                            "  <div class=\"msg-item-avatar\">\n" +
                            " <img src=\"" + this.mypicture + "\">\n" +
                            "  </div>\n" +
                            "  <div class=\"message\">\n" +
                            "  <div class=\"message-content is-me\">\n" + text + "</div>\n" + "</div>\n" + "</div>\n"
                    } else if (remoteUser) {
                        html = "<div class=\"msg-item not-me\">\n" +
                            "  <div class=\"msg-item-avatar\">\n" +
                            " <img src=\"" + _this.chatpicture + "\">\n" +
                            "  </div>\n" +
                            "  <div class=\"message\">\n" +
                            "  <div class=\"message-content not-me\">\n" + text + "</div>\n" + "</div>\n" + "</div>\n"
                    }
                    console.log(html)
                    this.content += html;
                },
                search_func(user, seller) {
                    var data = {
                        user: user,
                        seller: seller,
                    }
                    $.ajax({
                        type: 'GET',
                        url: "/conversation/search",
                        data: data,
                        ContentType: 'application/json;charset=utf-8',
                        success: function(data) {

                        },
                        error: function(xhr, type) {
                            console.log("Error");
                        }
                    });
                },
                getall_func(user) {
                    let _this = this;
                    var data = {
                        user: user,
                    }
                    $.ajax({
                        type: 'GET',
                        url: "http://8.130.103.251:8080/conversation/getall/user",
                        data: data,
                        ContentType: 'application/json;charset=utf-8',
                        success: function(data) {
                            _this.chaters = data.data;
                            console.log("chaters:" + _this.chaters.length)
                            console.log(JSON.stringify(_this.chaters))
                        },
                        error: function(xhr, type) {
                            console.log("Error");
                        }
                    });
                },
                getpic(user) {
                    let _this = this;
                    var data = {
                        name: user,
                    }
                    $.ajax({
                        type: 'GET',
                        url: "http://8.130.103.251:8080/user/getuser",
                        data: data,
                        ContentType: 'application/json;charset=utf-8',
                        success: function(data) {
                            console.log(data)
                            _this.mypicture = data.data.picture
                        },
                        error: function(xhr, type) {
                            console.log("Error");
                        }
                    });
                },
                getpic2(seller) {
                    let _this = this;
                    var data = {
                        name: seller,
                    }
                    $.ajax({
                        type: 'GET',
                        url: "http://8.130.103.251:8080/seller/getseller",
                        data: data,
                        ContentType: 'application/json;charset=utf-8',
                        success: function(data) {
                            _this.mypicture = data.data.picture
                            console.log("chaters:" + _this.chaters.length)
                            console.log(JSON.stringify(_this.chaters))
                        },
                        error: function(xhr, type) {
                            console.log("Error");
                        }
                    });
                },

                getall2_func(seller) {
                    let _this = this;
                    var data = {
                        seller: seller,
                    }
                    $.ajax({
                        type: 'GET',
                        url: "http://8.130.103.251:8080/conversation/getall/seller",
                        data: data,
                        ContentType: 'application/json;charset=utf-8',
                        success: function(data) {
                            _this.chaters = data.data;
                        },
                        error: function(xhr, type) {
                            console.log("Error");
                        }
                    });
                },

                history_search_func(from, to) {
                    let _this = this;
                    var data = {
                        from: from,
                        to: to,
                    }
                    $.ajax({
                        type: 'GET',
                        url: "http://8.130.103.251:8080/history/search",
                        data: data,
                        ContentType: 'application/json;charset=utf-8',
                        success: function(data) {
                            for (var i = 0; i < data.data.length; i++) {
                                console.log(data)
                                console.log(data.data)
                                console.log(data.data[i])
                                let json = JSON.parse(data.data[i])
                                console.log(json.from)
                                console.log(_this.user.username)
                                if (json.from === _this.user.username) {
                                    html = "<div class=\"msg-item is-me\">\n" +
                                        "  <div class=\"msg-item-avatar\">\n" +
                                        " <img src=\"" + _this.mypicture + "\">\n" +
                                        "  </div>\n" +
                                        "  <div class=\"message\">\n" +
                                        "  <div class=\"message-content is-me\">\n" + json.text + "</div>\n" + "</div>\n" + "</div>\n"
                                    _this.content += html
                                } else {
                                    html = "<div class=\"msg-item not-me\">\n" +
                                        "  <div class=\"msg-item-avatar\">\n" +
                                        " <img src=\"" + _this.chatpicture + "\">\n" +
                                        "  </div>\n" +
                                        "  <div class=\"message\">\n" +
                                        "  <div class=\"message-content not-me\">\n" + json.text + "</div>\n" + "</div>\n" + "</div>\n"
                                    _this.content += html
                                }
                            }
                        },
                        error: function(xhr, type) {
                            console.log("Error");
                        }
                    });
                },

                history_add_func(from, to, text) {
                    var data = {
                        from: from,
                        to: to,
                        text: text,
                    }
                    $.ajax({
                        type: 'POST',
                        url: "http://8.130.103.251:8080/history/add",
                        data: data,
                        ContentType: 'application/json;charset=utf-8',
                        success: function(data) {

                        },
                        error: function(xhr, type) {
                            console.log("Error");
                        }
                    });
                },


                init() {
                    this.user.username = getCookie("username");
                       if(getCookie("if_user")==1){
                       this.getall_func(this.user.username);
                       }else{
                        this.getall2_func(this.user.username);
                       }
                       if(getCookie("if_user")==1){
                        this.getpic(this.user.username);
                       }else{
                        this.getpic2(this.user.username);
                       }
                    // this.getall_func(this.user.username);
                    // this.getpic(this.user.username)
                    let username = this.user.username;
                    let _this = this;
                    if (typeof(WebSocket) == "undefined") {
                        console.log("您的浏览器不支持WebSocket");
                    } else {
                        console.log("您的浏览器支持WebSocket");
                        let socketUrl = "ws://8.130.103.251:8080/imserver/" + getCookie("username");
                        if (socket != null) {
                            socket.close();
                            socket = null;
                        }
                        // 开启一个websocket服务
                        socket = new WebSocket(socketUrl);
                        //打开事件
                        socket.onopen = function() {
                            console.log("websocket已打开");
                        };
                        //  浏览器端收消息，获得从服务端发送过来的文本消息
                        socket.onmessage = function(msg) {
                            console.log("收到数据====" + msg.data)
                            let data = JSON.parse(msg.data) // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
                            console.log(data.users)
                            if (data.users) { // 获取在线人员信息
                                _this.users = data.users.filter(user => user.username !== getCookie("username")) // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
                            } else {
                                // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
                                //  // {"from": "zhang", "text": "hello"}
                                
                                if (data.from === _this.chatUser) {
                                    _this.messages.push(data)
                                        // 构建消息内容
                                    _this.createContent(data.from, null, data.text)
                                }
                            }
                        };
                        //关闭事件
                        socket.onclose = function() {
                            console.log("websocket已关闭");
                        };
                        //发生了错误事件
                        socket.onerror = function() {
                            console.log("websocket发生了错误");
                        }
                    }
                }
            }
        });
    });
</script>
<script>
    //接口函数
    // function search_func(user,seller){
    //     var data ={
    //         user:user,
    //         seller:seller,
    //     }
    //     $.ajax({
    //         type: 'GET',
    //         url: "/conversation/search", 
    //         data: data,  
    //         ContentType: 'application/json;charset=utf-8',
    //         success: function(data) { 

    //         },
    //         error: function(xhr, type) {
    //             console.log("Error");
    //         }
    //     });
    // }

    // function addcon_func(user,seller){
    //     var data ={
    //         user:user,
    //         seller:seller,
    //     }
    //     $.ajax({
    //         type: 'GET',
    //         url: "/conversation/add", 
    //         data: data,  
    //         ContentType: 'application/json;charset=utf-8',
    //         success: function(data) { 

    //         },
    //         error: function(xhr, type) {
    //             console.log("Error");
    //         }
    //     });
    // }

    // function getall_func(user){
    //     var data ={
    //         user:user,
    //     }
    //     $.ajax({
    //         type: 'GET',
    //         url: "http://localhost:8080/conversation/getall/user", 
    //         data: data,  
    //         ContentType: 'application/json;charset=utf-8',
    //         success: function(data) { 
    //             this.chaters=data.data;
    //             console.log(this.chaters)
    //         },
    //         error: function(xhr, type) {
    //             console.log("Error");
    //         }
    //     });

    // }

    // function getall2_func(seller){
    //     var data ={
    //         seller:seller,
    //     }
    //     $.ajax({
    //         type: 'GET',
    //         url: "/conversation/getall/seller", 
    //         data: data,  
    //         ContentType: 'application/json;charset=utf-8',
    //         success: function(data) { 
    //             this.chaters=data.data;
    //         },
    //         error: function(xhr, type) {
    //             console.log("Error");
    //         }
    //     });
    // }

    // function history_search_func(from,to){
    //     var data ={
    //         from:from,
    //         to:to,
    //     }
    //     $.ajax({
    //         type: 'GET',
    //         url: "/history/search", 
    //         data: data,  
    //         ContentType: 'application/json;charset=utf-8',
    //         success: function(data) { 

    //         },
    //         error: function(xhr, type) {
    //             console.log("Error");
    //         }
    //     });
    // }

    // function history_add_func(from,to,text){
    //     var data ={
    //         from:from,
    //         to:to,
    //         text:text,
    //     }
    //     $.ajax({
    //         type: 'GET',
    //         url: "/history/add", 
    //         data: data,  
    //         ContentType: 'application/json;charset=utf-8',
    //         success: function(data) { 

    //         },
    //         error: function(xhr, type) {
    //             console.log("Error");
    //         }
    //     });
    // }
</script>
<script>
    $(document).ready(function (){
        //读取登录状态
        var if_login=$.cookie("status");
        //读取用户名
        var username=$.cookie("username");
        
        if(if_login==1){
            $("#login_region").text(username);
            $("#dropdown-login-item").css("display","none");
            $("#dropdown-exit-item").css("display","block");
            
        }else if(if_login==0){
            $("#login_region").text("登录/注册");
            $("#dropdown-login-item").css("display","block");
            $("#dropdown-exit-item").css("display","none");
        }
    });
</script>
<script>
    //导航栏顶部跳转数码专区
$("#digital-area").click(function(){
    $.cookie('pro_type',"数码配件",{ expires: 7 });
    window.open("tags.html");
});
</script>
<script>
    $("#person_center").click(function(){
        if($.cookie("status")==0){
            alert("请先登录！");
            return
        }
        else if($.cookie("status")==1){
            window.open("personalCenter.html");
        }
    })
</script>
<script>
    //退出按钮的点击事件
$("#dropdown-exit-item").on("click",function () { 
    $.cookie('username', null);
    $.cookie('status', '0', { expires: 7 });
    window.location.href="index.html"
})

</script>
</html>